package com.zline.foodraise.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.JsProjectAttention;
import com.zline.foodraise.entity.JsResourceBean;
import com.zline.foodraise.entity.JsShareBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.js.HostJSScope;
import com.zline.foodraise.js.MyWebViewSetting;
import com.zline.foodraise.listener.CanChildScrollUpCallback;
import com.zline.foodraise.listener.JsInvokeListener;
import com.zline.foodraise.util.ImageUtil;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.util.URLUtils;
import com.zline.foodraise.view.ScrollSwipeRefreshLayout;
import com.zline.foodraise.wx.WxShareUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by heshantao on 15/8/6.
 * 筹详情页
 */
@EActivity(R.layout.activity_project_product_detail)
public class ProjectDetailActivity extends ZlineActivity implements JsInvokeListener,CanChildScrollUpCallback{
    private static final String LOG_TAG = ProjectDetailActivity.class.getSimpleName();
    @ViewById(R.id.project_product_detail_wv)
    WebView wv;
    @ViewById(R.id.project_product_detail_web_srl)
    ScrollSwipeRefreshLayout swipeRefreshLayout;
    MyWebViewSetting mSetting;
    @Extra
    String url;
    @Extra
    String title;
    @ViewById(R.id.transparent_header_left_icon_iv)
    ImageView back_iv;
    @ViewById(R.id.transparent_header_title_tv)
    TextView title_tv;
    @ViewById(R.id.transparent_header_right_iv)
    ImageView header_right_iv;
    @ViewById(R.id.project_product_detail_header)
    RelativeLayout header_rl;
    @Bean
    HostJSScope hostJSScope;
    @Pref
    AppPref_ appPref;
    @Bean
    URLUtils urlUtils;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    @Bean
    ImageUtil imageUtil;
    @Bean
    WxShareUtil wxShareUtil;
    //分享结果
    String shareResult;
    MaterialDialog shareDialog;
    long projectId;
    int pageCount;
    //透明度最大值
    static final int MAX_ALPHA = 255;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @ViewById(R.id.exception_fl)
    FrameLayout exception_fl;
    //点击重试
    boolean isReLoad = false;
    //加载出错
    boolean isErro = false;
    @Bean
    NetworkUtil networkUtil;
    int isAttention;
    //滚动距离上面的距离
    double mMarginTop;
    int alpha;
    long userId;

    @AfterViews
    void doSomeAfterViews() {
        userId = appPref.userId().get();
        initWebView();
        initSwipRefreshLayout();
    }


    void initWebView() {
        mSetting = new MyWebViewSetting(wv, this);
        mSetting.setWebView();
        hostJSScope.setJsInvokeListener(this);
        wv.loadUrl(url);
        wv.setWebViewClient(new WebViewClient() {
            //出错界面
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                showErroView();
                LUtil.i(LOG_TAG, "______________erroCode________" + description);
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LUtil.i(LOG_TAG, "_________shouldOverrideUrlLoading________" + url);
                doLinkUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                LUtil.i(LOG_TAG, "_________onPageStarted________" + url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                LUtil.i(LOG_TAG, "____Host_____onPageFinished________" + url);
                if (!view.getSettings().getLoadsImagesAutomatically()) {
                    view.getSettings().setLoadsImagesAutomatically(true);
                }

                if (isReLoad && !isErro) {
                    exception_fl.setVisibility(View.GONE);
                    exception_rl.setVisibility(View.GONE);
                    wv.setVisibility(View.VISIBLE);
                }
                isErro = false;
                isReLoad = false;
                stopRefresh();
            }
        });
    }


    //初始化SwipRefreshLayout
    void initSwipRefreshLayout() {
        //设置加载颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setCanChildScrollUpCallback(this);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                wv.reload();
            }
        });
    }

    //停止刷新
    void stopRefresh() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    //显示网页加载出错情况
    void showErroView() {
        isErro = true;
        exception_fl.setVisibility(View.VISIBLE);
        exception_rl.setVisibility(View.VISIBLE);
        wv.setVisibility(View.GONE);
    }


    //登录后的回调
    @OnActivityResult(Constant.PROJECT_DETAIL_REQUEST_CODE)
    void onActivityResult(int resultCode) {
        switch (resultCode) {
            case Constant.LOGIN_RESULT_CODE:
                setUserInfo();
                break;
            default:
                break;
        }
    }

    //页面地址设置完成后回调
    @OnActivityResult(Constant.PROJECT_DETAIL_REQUEST_CODE)
    void onActivityResult(int resultCode, Intent data, @OnActivityResult.Extra String value) {
        switch (resultCode) {
            case Constant.ADDR_SET_RESULT_CODE:
                wv.loadUrl("javascript:choicedAddress(" + value + ")");
                wv.reload();
                break;
            default:
                break;
        }
    }

    //登录成功后将用户信息传递给JS 端
    void setUserInfo() {
        double latPoint = Double.parseDouble(appPref.latPoint().get());
        double lonPoint = Double.parseDouble(appPref.lonPoint().get());
        userId = appPref.userId().get();
        long cityId = appPref.cityId().get();
        String cityName = appPref.city().get();
        String userAddress = appPref.userAddress().get();
        String token = appPref.token().get();
        LUtil.i(LOG_TAG, "___setUserInfo_____返回___" + token + "________addr" + userAddress);
        wv.loadUrl("javascript:getUserInfo('" + latPoint + "','" + lonPoint + "','" + userId + "','" + cityId +
                "','" + cityName + "','" + userAddress + "','" + token + "')");

    }


    //处理带跳转链接的url
    void doLinkUrl(String url) {
        String goal = urlUtils.getUrlJumpTo(url);
        LUtil.i(LOG_TAG, "_____url________" + url + "____title_______" + title);
        if (goal.equals("support")) {//筹规格选择界面
            ProjectSpecificationsActivity_.intent(ProjectDetailActivity.this).url(url).start();
        } else if (goal.equals("chou-buy")) {//跳转到筹购买
            OrderGenerateActivity_.intent(ProjectDetailActivity.this).url(url).start();
        } else if (goal.equals("details")) {
            GraphicalTextActivity_.intent(ProjectDetailActivity.this).url(url).start();
        }
    }


    @Override
    public void jsInvoke(int flag) {
        switch (flag) {
            case Constant.WEB_LOGIN:
                //未登录先进行登录
                LoginActivity_.intent(this).startForResult(Constant.PROJECT_DETAIL_REQUEST_CODE);
                break;
            case Constant.WEB_SET_ADDR:
                Intent intent = new Intent(ProjectDetailActivity.this, SetAddrActivity_.class);
                startActivityForResult(intent, Constant.PROJECT_DETAIL_REQUEST_CODE);
                break;
            default:
                break;
        }
    }


    @Override
    public void jsInvoke(int flag, JSONObject jsonObject) {
        switch (flag) {
            case Constant.WEB_PROFILE_FLAG:
                //启动其他人profile页
                gotoProfile(jsonObject);
                break;
            case Constant.WEB_ATTENTION_FLAG:
                //启动项目关注列表
                gotoProjectAttentionList(jsonObject);
                break;
            case Constant.WEB_COMMENT_LIST_FLAG:
                gotoCommentList(jsonObject);
                break;
            case Constant.WEB_ADD_COMMENT_FLAG:
                //添加评论
                gotoAddComment(jsonObject);
                break;
            case Constant.WEB_SHARE_FLAG:
                share(jsonObject);
                break;
            case Constant.WEB_PROJECT_ATTENTION:
                getPorjectAttenionAndDownLoadTemplate(jsonObject);
                break;
            default:
                break;
        }
    }

    //通过滑动的距离变换title
    @UiThread
    @Override
    public void jsInvoke(double marginTop) {
        this.mMarginTop = marginTop;
        if (mMarginTop < 40) {
            header_rl.setBackgroundResource(R.mipmap.detail_project_header_bg);
            back_iv.setImageResource(R.mipmap.transparent_header_back);
            if (isAttention == 0) {
                header_right_iv.setImageResource(R.mipmap.normal_project_unattention);
            } else {
                header_right_iv.setImageResource(R.mipmap.normal_project_attention);
            }
        } else {
            header_rl.setBackgroundColor(Color.WHITE);
            if (mMarginTop > 420) {
                title_tv.setText(title);
            } else {
                title_tv.setText("");
            }
            alpha = (int) (1.2 * marginTop);
            if (alpha > MAX_ALPHA) {
                alpha = MAX_ALPHA;
            }
            if (alpha > MAX_ALPHA / 2) {
                back_iv.setImageResource(R.mipmap.common_header_back);
                if (isAttention == 0) {
                    header_right_iv.setImageResource(R.mipmap.scroll_project_unattention);
                } else {
                    header_right_iv.setImageResource(R.mipmap.normal_project_attention);
                }
            } else {
                back_iv.setImageResource(R.mipmap.transparent_header_back);
                if (isAttention == 0) {
                    header_right_iv.setImageResource(R.mipmap.normal_project_unattention);
                } else {
                    header_right_iv.setImageResource(R.mipmap.normal_project_attention);
                }
            }
            header_rl.getBackground().setAlpha(alpha);
        }

    }

    //预先下载模板信息和获取筹的关注状态
    void getPorjectAttenionAndDownLoadTemplate(JSONObject jsonObject) {
        if (jsonObject != null) {
            String info = jsonObject.toString();
            Gson gson = new Gson();
            JsProjectAttention projectAttention = gson.fromJson(info, JsProjectAttention.class);
            projectId = projectAttention.getProjectId();
            isAttention = projectAttention.getIsFollowed();
            if (isAttention == 0) {
                header_right_iv.setImageResource(R.mipmap.normal_project_unattention);
            } else {
                header_right_iv.setImageResource(R.mipmap.normal_project_attention);
            }
        }

    }

    //启动评论列表
    void gotoCommentList(JSONObject jsonObject) {
        String info = jsonObject.toString();
        Gson gson = new Gson();
        JsResourceBean jsResourceBean = gson.fromJson(info, JsResourceBean.class);
        CommentListActivity_.intent(this).jsResourceBean(jsResourceBean).start();

    }

    //启动个人Profile页
    void gotoProfile(JSONObject jsonObject) {
        String info = jsonObject.toString();
        Gson gson = new Gson();
        JsResourceBean jsResourceBean = gson.fromJson(info, JsResourceBean.class);
        if (jsResourceBean == null) return;
        PersonalHomePageActivity_.intent(this).userId(jsResourceBean.getUserId()).start();
    }


    //启动筹用户列表
    void gotoProjectAttentionList(JSONObject jsonObject) {
        String info = jsonObject.toString();
        Gson gson = new Gson();
        JsResourceBean jsResourceBean = gson.fromJson(info, JsResourceBean.class);
        if (jsResourceBean == null) return;
        ProjectAttentionListActivity_.intent(this).projectId(jsResourceBean.getProjectId()).start();
    }


    //添加评论
    void gotoAddComment(JSONObject jsonObject) {
        String info = jsonObject.toString();
        Gson gson = new Gson();
        JsResourceBean jsResourceBean = gson.fromJson(info, JsResourceBean.class);
        if (jsResourceBean == null) return;
        ReleaseCommentActvity_.intent(this).resourceId(jsResourceBean.getResourceId()).
                resourceType(jsResourceBean.getType()).flag(Constant.ADD_COMMENT_FLAG).start();
    }


    //根据参数处理分享事件
    void share(JSONObject jsonObject) {
        String shareInfo = jsonObject.toString();
        Gson gson = new Gson();
        JsShareBean shareBean = gson.fromJson(shareInfo, JsShareBean.class);
        if (shareBean == null) return;
        int shareContentInt = shareBean.getIsNoTemplate();
        if (shareContentInt == 1) {//分享链接
            wxShareUtil.setShareContentType(Constant.URL_SHARE_TYPE);
            String projectPicUrl = shareBean.getLogo();
            wxShareUtil.setSharePicPath(projectPicUrl);
            String title = shareBean.getTitle();
            wxShareUtil.setShareTitle(title);
            String des = shareBean.getDesc();
            wxShareUtil.setShareDescipt(des);
            String url = shareBean.getUrl();
            LUtil.i(LOG_TAG, "_______分享URl_____" + url);
            wxShareUtil.setShareUrl(url);
            wxShareUtil.openShareDialog();
        } else if (shareContentInt == 0) {//分享模板
            TemplateChooseActivity_.intent(ProjectDetailActivity.this).projectId(projectId).start();

        }
    }

    //分享结果对话框
    void showShareResultDialog() {
        shareDialog = new MaterialDialog.Builder(this)
                .title(R.string.share)
                .titleGravity(GravityEnum.CENTER)
                .content(shareResult)
                .positiveText(R.string.ok)
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        super.onNegative(dialog);
                    }

                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        super.onPositive(dialog);
                        shareDialog.dismiss();
                    }
                })
                .show();
    }




    //改变项目的关注状态
    void changeProjectAttention() {
        if (networkUtil.isNetworkAvailable()) {
            if (isAttention == 0) {
                requestAttentionProject();
            } else {
                requestCancelAttentionProject();
            }

        } else {
            TUtil.showShort(ProjectDetailActivity.this, R.string.no_network);
        }
    }


    //请求关注项目
    void requestAttentionProject() {
        httpOperator.requestAttentionProject(httpUtil, projectId, requestAttentionHandler);
    }

    //请求关注项目回调
    AsyncHttpResponseHandler requestAttentionHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestAttentionHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        setHeaderAttention(true);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);

        }
    };

    //请求关注项目
    void requestCancelAttentionProject() {
        httpOperator.requestCancelAttentionProject(httpUtil, projectId, requestCancelAttentionHandler);
    }

    //请求取消项目关注回调
    AsyncHttpResponseHandler requestCancelAttentionHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestCancelAttentionHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        setHeaderAttention(false);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);

        }
    };


    //设置关注状态
    void setHeaderAttention(boolean attention) {
        if (attention) {
            isAttention = 1;
            header_right_iv.setImageResource(R.mipmap.normal_project_attention);

        } else {
            isAttention = 0;
            if (mMarginTop < 40) {
                header_right_iv.setImageResource(R.mipmap.normal_project_unattention);
            } else {
                if (alpha > MAX_ALPHA / 2) {
                    header_right_iv.setImageResource(R.mipmap.scroll_project_unattention);
                } else {
                    header_right_iv.setImageResource(R.mipmap.normal_project_unattention);
                }
            }
        }
    }








    @Override
    public boolean canSwipeRefreshChildScrollUp() {
        return wv.getScrollY() > Constant.WEBVIEW_SCROLL_Y;
    }





    @Click({R.id.transparent_header_left_icon_iv, R.id.transparent_header_right_iv, R.id.reload_tv})
    void OnClick(View view) {
        switch (view.getId()) {
            case R.id.transparent_header_left_icon_iv:
                goback();
                break;
            case R.id.transparent_header_right_iv:
                if (userId > 0) {
                    changeProjectAttention();
                } else {
                    LoginActivity_.intent(this).startForResult(Constant.PROJECT_DETAIL_REQUEST_CODE);
                }
                break;
            case R.id.reload_tv:
                isReLoad = true;
                wv.reload();
                break;
            default:
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        shareResult = appPref.shareResult().get();
        if (!StringUtils.isBlank(shareResult)) {
            showShareResultDialog();
            appPref.edit().shareResult().put("").apply();
        }
        hostJSScope.setJsInvokeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        hostJSScope.setJsInvokeListener(null);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}
